package ar.com.lemil.bb.http;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

import ar.com.lemil.bb.http.vo.HttpPing;
import ar.com.lemil.bb.utils.log.Logger;

public class HttpRequestUtils {

	public HttpPing httpPing(String url, long ttl) throws Exception {
		HttpConnection hc = null;
		HttpPing ping = new HttpPing(false,0,ttl,url);
		long startime = System.currentTimeMillis();
		long elapsed = 0;
		try {
			String sep = url.endsWith(";") ? "" : ";" ;
			String furl = url + sep + "ConnectionTimeout=" + ttl ; // + ";";
			Logger.getInstance().log("Ping to :" + furl);
			hc = (HttpConnection) Connector.open(furl);
			hc.setRequestMethod(HttpConnection.GET);
			hc.setRequestProperty("User-Agent","Profile/MIDP-2.0 Configuration/CLDC-1.0 ReclamosMobiles/1.0");
			int rc = hc.getResponseCode(); 
			elapsed = System.currentTimeMillis() - startime;
			ping.setTime(elapsed);
			ping.setResponseCode(rc);
			ping.setSuccess(true);
		} catch (Exception ex) {
			elapsed = System.currentTimeMillis() - startime;
			ping.setTime(ttl);
			ping.setSuccess(false);
		} finally {
			try { hc.close(); } catch (Exception e) {}
		}
		return ping;
	}
}
